<template>
  <div class="font-manager">
    <!-- 顶部搜索栏 -->
    <div class="search-header">
      <div class="search-controls">
        <a-input-search v-model:value="searchKeyword" placeholder="搜索图标..." allow-clear @search="onSearch" @change="onSearchChange" class="search-input" size="large">
          <template #prefix>
            <search-outlined />
          </template>
        </a-input-search>

        <!-- 管理员上传按钮 -->
        <div v-if="isAdmin" class="upload-btn">
          <a-upload :show-upload-list="false" :custom-request="handleFontUpload" accept=".svg" :disabled="uploading" :multiple="true">
            <a-button type="primary" :loading="uploading">
              <template #icon>
                <UploadOutlined />
              </template>
              上传图标
            </a-button>
          </a-upload>
        </div>

        <!-- 管理员批量操作按钮 -->
        <div v-if="isAdmin" class="batch-controls">
          <a-button type="default" @click="toggleBatchMode" :class="{ 'batch-mode-active': batchMode }">
            <template #icon>
              <CheckSquareOutlined v-if="batchMode" />
              <BorderOutlined v-else />
            </template>
            {{ batchMode ? '退出批量' : '批量管理' }}
          </a-button>
        </div>

        <div class="stats-info">
          <a-typography-text type="secondary">
            当前展示 <strong>{{ fonts.length }}</strong> 个图标，总共 <strong>{{ serverTotal }}</strong> 个图标
            <span v-if="searchKeyword">，搜索："{{ searchKeyword }}"</span>
            <span v-if="batchMode && selectedCount > 0"
              >，已选中 <strong>{{ selectedCount }}</strong> 个</span
            >
          </a-typography-text>
        </div>
      </div>

      <!-- 批量操作工具栏 -->
      <div v-if="batchMode && isAdmin" class="batch-toolbar">
        <div class="batch-actions">
          <a-checkbox v-model:checked="isAllSelected" :indeterminate="isIndeterminate" @change="handleSelectAll"> 全选 </a-checkbox>

          <a-button type="text" size="small" @click="clearSelection" :disabled="selectedCount === 0"> 清空选择 </a-button>

          <a-button type="primary" danger :disabled="selectedCount === 0" :loading="batchDeleting" @click="handleBatchDelete">
            <template #icon>
              <DeleteOutlined />
            </template>
            删除选中 ({{ selectedCount }})
          </a-button>
        </div>
      </div>
    </div>

    <!-- 主内容区域 -->
    <div class="main-content">
      <!-- 左侧图标列表 -->
      <div class="font-list-panel" ref="scrollContainer" @scroll="handleScroll">
        <div class="font-list-content">
          <!-- 加载状态 -->
          <div v-if="loading && fonts.length === 0" class="loading-state">
            <div class="loading-spinner"></div>
            <div class="loading-text">正在加载图标库...</div>
          </div>

          <!-- 图标网格 -->
          <div v-else-if="fonts.length > 0" class="fonts-grid">
            <div class="font-card" v-for="font in fonts" :key="font.id" :class="{ selected: batchMode && selectedIds.includes(font.id), 'batch-mode': batchMode }" @click="batchMode ? toggleSelection(font.id) : null">
              <!-- 批量选择复选框 -->
              <div v-if="batchMode && isAdmin" class="batch-checkbox">
                <a-checkbox :checked="selectedIds.includes(font.id)" @change="toggleSelection(font.id)" @click.stop />
              </div>

              <!-- 图标图标 - 使用动态渲染的SVG -->
              <div class="font-image" v-html="getStyledSVG(font)" :style="{ width: iconSize + 'px', height: iconSize + 'px' }"></div>

              <!-- 图标信息 -->
              <div class="font-content">
                <p class="font-name" :title="font.original_name">
                  {{ font.original_name }}
                </p>
                <div class="font-details">
                  <span class="font-size">{{ formatFileSize(font.file_size) }}</span>
                  <span class="font-date">{{ formatDate(font.created_at) }}</span>
                </div>
              </div>

              <!-- 操作菜单 -->
              <div v-if="!batchMode" class="font-actions" @click="stopPropagation">
                <a-dropdown placement="bottomRight" :trigger="['click']">
                  <a-button type="text" size="small" class="menu-trigger">
                    <template #icon>
                      <MoreOutlined />
                    </template>
                  </a-button>
                  <template #overlay>
                    <a-menu>
                      <a-menu-item key="copy" @click="handleCopySVG(font)">
                        <template #icon>
                          <CopyOutlined />
                        </template>
                        复制SVG
                      </a-menu-item>

                      <a-menu-item key="download-svg" @click="handleDownloadSVG(font)">
                        <template #icon>
                          <DownloadOutlined />
                        </template>
                        下载SVG
                      </a-menu-item>
                      <a-menu-item key="download-png" @click="handleDownloadPNG(font)">
                        <template #icon>
                          <FileImageOutlined />
                        </template>
                        下载PNG
                      </a-menu-item>
                      <a-menu-item key="copy-vue3" @click="handleCopyAsVue3Component(font)">
                        <template #icon>
                          <CopyOutlined />
                        </template>
                        复制成Vue3组件
                      </a-menu-item>
                      <!-- 管理员专用功能 -->
                      <template v-if="isAdmin">
                        <a-menu-divider />
                        <a-menu-item key="delete" danger @click="handleDeleteFont(font)" :disabled="deletingIds.includes(font.id)">
                          <template #icon>
                            <DeleteOutlined />
                          </template>
                          删除图标
                        </a-menu-item>
                      </template>
                    </a-menu>
                  </template>
                </a-dropdown>
              </div>
            </div>
          </div>

          <!-- 加载更多状态 -->
          <div v-if="loadingMore" class="loading-more">
            <div class="loading-spinner small"></div>
            <div class="loading-text">正在加载更多...</div>
          </div>

          <!-- 没有更多数据 -->
          <div v-if="fonts.length > 0 && !hasMore && !loading" class="no-more">
            <a-typography-text type="secondary">已加载全部图标</a-typography-text>
          </div>

          <!-- 空状态 -->
          <div v-if="!loading && fonts.length === 0" class="empty-state">
            <div class="empty-content">
              <div class="empty-icon">📄</div>
              <div class="empty-text">{{ searchKeyword ? '未找到匹配的图标' : '暂无图标文件' }}</div>
              <div class="empty-suggestion" v-if="searchKeyword">试试调整搜索关键词</div>
              <div v-if="isAdmin && !searchKeyword" class="empty-actions">
                <a-upload :show-upload-list="false" :custom-request="handleFontUpload" accept=".svg" :disabled="uploading" :multiple="true">
                  <a-button type="primary" :loading="uploading"> 上传图标 </a-button>
                </a-upload>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧设置面板 -->
      <div class="settings-panel">
        <div class="settings-content">
          <!-- 图标大小 -->
          <div class="setting-group">
            <div class="setting-label">图标大小</div>
            <div class="setting-control">
              <a-slider v-model:value="iconSize" :min="16" :max="64" :step="2" />
              <a-input-number v-model:value="iconSize" :min="16" :max="64" size="small" />
            </div>
          </div>

          <!-- 图标颜色 -->
          <div class="setting-group">
            <div class="setting-label">图标颜色</div>
            <div class="color-picker-container">
              <div class="color-input-row">
                <input type="color" v-model="iconColor" class="color-picker" />
                <a-input v-model:value="iconColor" placeholder="#000000" size="small" class="color-input" />
              </div>
              <div class="preset-colors">
                <div class="preset-colors-label">预设颜色</div>
                <div class="preset-colors-grid">
                  <div v-for="color in presetColors" :key="color" class="preset-color-item" :class="{ active: iconColor === color }" :style="{ backgroundColor: color }" @click="iconColor = color" :title="color"></div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { SearchOutlined, CopyOutlined, DownloadOutlined, UploadOutlined, MoreOutlined, DeleteOutlined, FileImageOutlined, CheckSquareOutlined, BorderOutlined } from '@ant-design/icons-vue'
import { useUserStore } from '@/stores/user'
import { getFontsList, uploadFont, deleteFont } from '@/utils/api'

const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const loadingMore = ref(false)
const uploading = ref(false)
const searchKeyword = ref('')
const fonts = ref([])
const serverTotal = ref(0) // 服务器端的总数
const deletingIds = ref([])

// 批量操作相关
const batchMode = ref(false)
const selectedIds = ref([])
const batchDeleting = ref(false)

// 分页相关
const currentPage = ref(1)
const pageSize = ref(120)
const hasMore = ref(true)

// 滚动容器引用
const scrollContainer = ref(null)

// 权限检查
const isAdmin = ref(false)

// 设置面板相关
const iconSize = ref(26)
const iconColor = ref('#595959')

// 预设颜色
const presetColors = ['#000000', '#1890ff', '#52c41a', '#faad14', '#f5222d', '#722ed1', '#13c2c2', '#eb2f96', '#fa541c', '#595959']

// 计算属性
const selectedCount = computed(() => selectedIds.value.length)
const isAllSelected = computed(() => fonts.value.length > 0 && selectedIds.value.length === fonts.value.length)
const isIndeterminate = computed(() => selectedIds.value.length > 0 && selectedIds.value.length < fonts.value.length)

/**
 * 检查管理员权限
 */
const checkAdminPermission = () => {
  isAdmin.value = userStore.user && userStore.user.username === 'woaichitudouo'
}

/**
 * 切换批量模式
 */
const toggleBatchMode = () => {
  batchMode.value = !batchMode.value
  if (!batchMode.value) {
    // 退出批量模式时清空选择
    clearSelection()
  }
}

/**
 * 切换单个图标选择状态
 */
const toggleSelection = (fontId) => {
  const index = selectedIds.value.indexOf(fontId)
  if (index > -1) {
    selectedIds.value.splice(index, 1)
  } else {
    selectedIds.value.push(fontId)
  }
}

/**
 * 全选/取消全选
 */
const handleSelectAll = (checked) => {
  if (checked) {
    selectedIds.value = fonts.value.map((font) => font.id)
  } else {
    selectedIds.value = []
  }
}

/**
 * 清空选择
 */
const clearSelection = () => {
  selectedIds.value = []
}

/**
 * 批量删除图标
 */
const handleBatchDelete = () => {
  if (selectedCount.value === 0) {
    message.warning('请先选择要删除的图标')
    return
  }

  const selectedFonts = fonts.value.filter((font) => selectedIds.value.includes(font.id))
  const fontNames = selectedFonts.map((font) => font.original_name).slice(0, 3)
  const nameDisplay = fontNames.join('、') + (selectedFonts.length > 3 ? `等${selectedFonts.length}个图标` : '')

  Modal.confirm({
    title: '确认批量删除',
    content: `确定要删除 ${nameDisplay} 吗？此操作不可恢复。`,
    okText: '确认删除',
    okType: 'danger',
    cancelText: '取消',
    onOk: async () => {
      try {
        batchDeleting.value = true

        // 并发删除所有选中的图标
        const deletePromises = selectedIds.value.map((fontId) => deleteFont(fontId))
        await Promise.all(deletePromises)

        message.success(`成功删除 ${selectedCount.value} 个图标`)

        // 删除成功后，从当前列表中移除这些项
        fonts.value = fonts.value.filter((font) => !selectedIds.value.includes(font.id))

        // 更新服务器总数
        serverTotal.value = Math.max(0, serverTotal.value - selectedCount.value)

        // 更新hasMore状态
        hasMore.value = fonts.value.length < serverTotal.value

        // 清空选择
        clearSelection()

        // 如果删除后当前页没有数据了，尝试加载更多
        if (fonts.value.length === 0 && hasMore.value) {
          await fetchFonts()
        }
      } catch (error) {
        console.error('批量删除图标失败:', error)
        message.error(error.message || '批量删除图标失败')
      } finally {
        batchDeleting.value = false
      }
    }
  })
}

/**
 * 获取并应用样式的SVG
 * @param {Object} font - 图标对象
 * @param {Number} size - 图标大小，可选，用于特殊情况（如预览）
 * @returns {String} 处理后的SVG字符串
 */
const getStyledSVG = (font, size = null) => {
  if (!font) return ''

  // 使用固定的初始尺寸，避免因为iconSize变化导致重新渲染
  const targetSize = size || 24
  const svgUrl = getFontUrl(font.file_path)

  // 返回一个容器，尺寸会通过CSS类和JavaScript动态更新
  return `<div class="svg-container" data-font-id="${font.id}" data-svg-url="${svgUrl}" data-size="${targetSize}" style="width: ${targetSize}px; height: ${targetSize}px; display: flex; align-items: center; justify-content: center;"></div>`
}

/**
 * 处理SVG内容
 * @param {String} svgContent - 原始SVG内容
 * @param {Number} size - 图标大小
 * @returns {String} 处理后的SVG内容
 */
const processSVGContent = (svgContent, size) => {
  try {
    // 解析SVG
    const parser = new DOMParser()
    const svgDoc = parser.parseFromString(svgContent, 'image/svg+xml')
    const svgElement = svgDoc.documentElement

    // 检查解析是否成功
    if (!svgElement || svgElement.nodeName === 'parsererror') {
      console.error('SVG解析失败')
      return svgContent
    }

    // 设置尺寸
    svgElement.setAttribute('width', size)
    svgElement.setAttribute('height', size)

    // 保留原始viewBox，如果没有则设置一个
    if (!svgElement.getAttribute('viewBox')) {
      svgElement.setAttribute('viewBox', '0 0 24 24')
    }

    // 应用颜色到所有图形元素
    const graphicElements = svgElement.querySelectorAll('path, line, circle, rect, ellipse, polygon, polyline')
    graphicElements.forEach((el) => {
      const currentStroke = el.getAttribute('stroke')
      const currentFill = el.getAttribute('fill')

      // 应用描边颜色
      if (currentStroke && currentStroke !== 'none') {
        el.setAttribute('stroke', iconColor.value)
      }

      // 应用填充颜色
      if (currentFill && currentFill !== 'none') {
        el.setAttribute('fill', iconColor.value)
      }

      // 如果既没有stroke也没有fill，默认应用颜色到fill
      if ((!currentStroke || currentStroke === 'none') && (!currentFill || currentFill === 'none')) {
        el.setAttribute('fill', iconColor.value)
      }
    })

    const result = new XMLSerializer().serializeToString(svgElement)

    // 简单验证
    if (result.length < 50) {
      console.warn('处理后的SVG内容异常短，使用原始内容')
      return svgContent
    }

    return result
  } catch (error) {
    console.error('处理SVG内容失败:', error, '原始内容长度:', svgContent.length)
    return svgContent
  }
}

// SVG缓存，避免重复请求
const svgCache = new Map()

/**
 * 加载并处理SVG内容（仅首次加载）
 * @param {HTMLElement} container - SVG容器元素
 */
const loadAndProcessSVG = async (container) => {
  const svgUrl = container.dataset.svgUrl
  const size = parseInt(container.dataset.size)
  const fontId = container.dataset.fontId

  try {
    // 添加加载状态
    container.innerHTML = '<div class="svg-loading">加载中...</div>'

    // 检查缓存
    let svgContent
    if (svgCache.has(svgUrl)) {
      svgContent = svgCache.get(svgUrl)
    } else {
      // 获取SVG内容并缓存
      const response = await fetch(svgUrl)
      if (!response.ok) throw new Error('加载失败')

      svgContent = await response.text()
      svgCache.set(svgUrl, svgContent)
    }

    // 处理SVG内容
    const processedSVG = processSVGContent(svgContent, size)

    // 显示处理后的SVG
    container.innerHTML = processedSVG

    // 标记为已加载
    container.setAttribute('data-loaded', 'true')
  } catch (error) {
    console.error('加载SVG失败:', error)
    container.innerHTML = '<div class="svg-error">加载失败</div>'
  }
}

/**
 * 获取图标列表
 * @param {boolean} isLoadMore - 是否为加载更多操作
 */
const fetchFonts = async (isLoadMore = false) => {
  try {
    if (!isLoadMore) {
      loading.value = true
      currentPage.value = 1
      hasMore.value = true
    } else {
      if (!hasMore.value || loadingMore.value) return
      loadingMore.value = true
      // 加载更多时，先递增页码
      currentPage.value++
    }

    const params = {
      page: currentPage.value,
      limit: pageSize.value,
      name: searchKeyword.value
    }

    const response = await getFontsList(params)

    if (response.data) {
      const newFonts = response.data.fonts || []
      const total = response.data.pagination?.total || 0

      // 更新服务器总数
      serverTotal.value = total

      if (isLoadMore) {
        // 加载更多：追加数据
        fonts.value = [...fonts.value, ...newFonts]
      } else {
        // 首次加载或搜索：替换数据
        fonts.value = newFonts
      }

      // 检查是否还有更多数据（基于服务器总数）
      hasMore.value = fonts.value.length < serverTotal.value
    }
  } catch (error) {
    console.error('获取图标列表失败:', error)
    message.error(error.message || '获取图标列表失败')
  } finally {
    loading.value = false
    loadingMore.value = false

    // 处理新加载的SVG（首次加载或加载更多）
    await nextTick()
    setTimeout(async () => {
      const containers = document.querySelectorAll('.svg-container:not([data-loaded])')
      for (const container of containers) {
        await loadAndProcessSVG(container)

        // 加载完成后立即应用当前的iconSize
        if (container.getAttribute('data-loaded') === 'true') {
          const svgElement = container.querySelector('svg')
          if (svgElement) {
            container.style.width = iconSize.value + 'px'
            container.style.height = iconSize.value + 'px'
            container.dataset.size = iconSize.value
            svgElement.setAttribute('width', iconSize.value)
            svgElement.setAttribute('height', iconSize.value)
          }
        }
      }
    }, 100)
  }
}

/**
 * 获取图标文件URL
 */
const getFontUrl = (filePath) => {
  return `${import.meta.env.VITE_APP_API_BASE_URL}${filePath}`
}

/**
 * 格式化文件大小
 */
const formatFileSize = (bytes) => {
  if (!bytes) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

/**
 * 格式化日期
 */
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

/**
 * 阻止事件冒泡
 */
const stopPropagation = (event) => {
  event.stopPropagation()
}

/**
 * 上传图标处理
 */
const handleFontUpload = async (options) => {
  const { file } = options

  try {
    // 检查文件类型
    if (!file.type.includes('svg') && !file.name.toLowerCase().endsWith('.svg')) {
      message.error(`${file.name} 不是SVG格式文件`)
      return
    }

    // 检查文件大小 (10MB)
    if (file.size > 10 * 1024 * 1024) {
      message.error(`${file.name} 文件大小超过10MB`)
      return
    }

    uploading.value = true
    await uploadFont(file)
    message.success(`${file.name} 上传成功`)

    // 刷新列表
    await fetchFonts()
  } catch (error) {
    console.error('上传图标失败:', error)
    message.error(`${file.name} 上传失败: ${error.message || '未知错误'}`)
  } finally {
    uploading.value = false
  }
}

/**
 * 删除图标
 */
const handleDeleteFont = (font) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除图标 "${font.original_name}" 吗？此操作不可恢复。`,
    okText: '确认删除',
    okType: 'danger',
    cancelText: '取消',
    onOk: async () => {
      try {
        deletingIds.value.push(font.id)
        await deleteFont(font.id)
        message.success('图标删除成功')

        // 删除成功后，从当前列表中移除该项
        fonts.value = fonts.value.filter((f) => f.id !== font.id)

        // 服务器总数减1
        serverTotal.value = Math.max(0, serverTotal.value - 1)

        // 更新hasMore状态
        hasMore.value = fonts.value.length < serverTotal.value
      } catch (error) {
        console.error('删除图标失败:', error)
        message.error(error.message || '删除图标失败')
      } finally {
        deletingIds.value = deletingIds.value.filter((id) => id !== font.id)
      }
    }
  })
}

/**
 * 检查登录状态
 */
const checkLoginStatus = () => {
  if (!userStore.isAuthenticated) {
    window.dispatchEvent(new CustomEvent('openLogin'))
    return false
  }
  return true
}

/**
 * 复制SVG内容
 */
const handleCopySVG = async (font) => {
  if (!checkLoginStatus()) return
  if (!font) return

  try {
    const svgUrl = getFontUrl(font.file_path)

    // 优先从缓存获取
    let originalSvgContent
    if (svgCache.has(svgUrl)) {
      originalSvgContent = svgCache.get(svgUrl)
    } else {
      const response = await fetch(svgUrl)
      const content = await response.text()
      svgCache.set(svgUrl, content)
      originalSvgContent = content
    }

    // 应用当前样式设置到SVG内容
    const processedSvgContent = processSVGContent(originalSvgContent, iconSize.value)

    await navigator.clipboard.writeText(processedSvgContent)
    message.success(`已复制 ${font.original_name} 的SVG内容`)
  } catch (error) {
    console.error('复制SVG失败:', error)
    message.error('复制SVG失败')
  }
}

/**
 * 复制成Vue3组件
 */
const handleCopyAsVue3Component = async (font) => {
  if (!checkLoginStatus()) return
  if (!font) return

  try {
    const svgUrl = getFontUrl(font.file_path)

    // 优先从缓存获取
    let originalSvgContent
    if (svgCache.has(svgUrl)) {
      originalSvgContent = svgCache.get(svgUrl)
    } else {
      const response = await fetch(svgUrl)
      const content = await response.text()
      svgCache.set(svgUrl, content)
      originalSvgContent = content
    }

    // 应用当前样式设置到SVG内容
    const processedSvgContent = processSVGContent(originalSvgContent, iconSize.value)

    // 生成Vue3组件代码 - 使用数组方式避免语法冲突
    const lines = []
    lines.push('<!-- Vue3 Icon Component -->')
    lines.push('<template>')
    lines.push('  <div class="icon-wrapper" :style="{ width: size + \'px\', height: size + \'px\' }">')
    lines.push('    ' + processedSvgContent.replace(/width="\d+"/, ':width="size"').replace(/height="\d+"/, ':height="size"'))
    lines.push('  </div>')
    lines.push('</template>')
    lines.push('')
    lines.push('<script setup>')
    lines.push('defineProps({')
    lines.push('  size: {')
    lines.push('    type: Number,')
    lines.push('    default: ' + iconSize.value)
    lines.push('  }')
    lines.push('})')
    lines.push('</' + 'script>') // 分割避免解析冲突
    lines.push('')
    lines.push('<style scoped>')
    lines.push('.icon-wrapper {')
    lines.push('  display: inline-flex;')
    lines.push('  align-items: center;')
    lines.push('  justify-content: center;')
    lines.push('}')
    lines.push('</' + 'style>') // 分割避免解析冲突

    const componentCode = lines.join('\n')

    await navigator.clipboard.writeText(componentCode)
    message.success(`已复制 ${font.original_name} 的Vue3组件代码`)
    // 使用 nextTick 确保在 Vue 上下文中调用 message
    await nextTick()
  } catch (error) {
    console.error('复制Vue3组件失败:', error)
    await nextTick()
    message.error('复制Vue3组件失败')
  }
}

/**
 * 下载SVG文件
 */
const handleDownloadSVG = async (font) => {
  if (!checkLoginStatus()) return
  if (!font) return

  try {
    const svgUrl = getFontUrl(font.file_path)

    // 优先从缓存获取
    let originalSvgContent
    if (svgCache.has(svgUrl)) {
      originalSvgContent = svgCache.get(svgUrl)
    } else {
      const response = await fetch(svgUrl)
      const content = await response.text()
      svgCache.set(svgUrl, content)
      originalSvgContent = content
    }

    // 应用当前样式设置到SVG内容
    const processedSvgContent = processSVGContent(originalSvgContent, iconSize.value)

    const blob = new Blob([processedSvgContent], { type: 'image/svg+xml' })
    const url = URL.createObjectURL(blob)

    const link = document.createElement('a')
    link.href = url
    link.download = font.original_name
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)

    URL.revokeObjectURL(url)
    message.success(`已下载 ${font.original_name}`)
  } catch (error) {
    console.error('下载SVG失败:', error)
    message.error('下载SVG失败')
  }
}

/**
 * 下载PNG文件
 */
const handleDownloadPNG = async (font) => {
  if (!checkLoginStatus()) return
  if (!font) return

  try {
    const svgUrl = getFontUrl(font.file_path)

    // 优先从缓存获取
    let originalSvgContent
    if (svgCache.has(svgUrl)) {
      originalSvgContent = svgCache.get(svgUrl)
    } else {
      const response = await fetch(svgUrl)
      const content = await response.text()
      svgCache.set(svgUrl, content)
      originalSvgContent = content
    }

    // 应用当前样式设置到SVG内容
    const processedSvgContent = processSVGContent(originalSvgContent, 300) // 使用较大尺寸用于PNG导出

    // 创建SVG元素
    const svgElement = new DOMParser().parseFromString(processedSvgContent, 'image/svg+xml').documentElement

    // 获取SVG尺寸
    const width = 300 // 固定使用300px
    const height = 300

    // 创建canvas
    const canvas = document.createElement('canvas')
    const ctx = canvas.getContext('2d')
    canvas.width = width * 2 // 2倍分辨率
    canvas.height = height * 2
    ctx.scale(2, 2)

    // 创建图片
    const img = new Image()
    const svgBlob = new Blob([processedSvgContent], { type: 'image/svg+xml;charset=utf-8' })
    const url = URL.createObjectURL(svgBlob)

    img.onload = () => {
      // 设置白色背景
      ctx.fillStyle = '#ffffff'
      ctx.fillRect(0, 0, width, height)

      // 绘制SVG
      ctx.drawImage(img, 0, 0, width, height)

      // 转换为PNG并下载
      canvas.toBlob((blob) => {
        const pngUrl = URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = pngUrl
        link.download = font.original_name.replace(/\.svg$/i, '.png')
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)

        URL.revokeObjectURL(pngUrl)
        URL.revokeObjectURL(url)
        message.success(`已下载 ${font.original_name.replace(/\.svg$/i, '.png')}`)
      }, 'image/png')
    }

    img.onerror = () => {
      URL.revokeObjectURL(url)
      message.error('转换PNG失败')
    }

    img.src = url
  } catch (error) {
    console.error('下载PNG失败:', error)
    message.error('下载PNG失败')
  }
}

/**
 * 滚动监听处理
 */
const handleScroll = () => {
  if (!scrollContainer.value || !hasMore.value || loadingMore.value) return

  const { scrollTop, scrollHeight, clientHeight } = scrollContainer.value

  // 当滚动到距离底部100px时触发加载更多
  if (scrollTop + clientHeight >= scrollHeight - 100) {
    fetchFonts(true)
  }
}

// 事件处理
const onSearch = async () => {
  await fetchFonts()
}

const onSearchChange = async () => {
  await fetchFonts()
}

// 生命周期
onMounted(async () => {
  checkAdminPermission()
  await fetchFonts()
  // fetchFonts中的finally已经会处理SVG，不需要重复处理
})

// 监听用户状态变化，动态更新管理员权限
watch(
  () => userStore.user,
  () => {
    checkAdminPermission()
  },
  { immediate: true }
)

// 监听搜索变化
watch(
  searchKeyword,
  async () => {
    await fetchFonts()
    // fetchFonts中的finally已经会处理新加载的SVG，不需要重复处理
  },
  { debounce: 300 }
)

// 监听图标大小变化，只更新尺寸
watch(iconSize, () => {
  // 延迟执行，确保DOM更新完成
  setTimeout(() => {
    const containers = document.querySelectorAll('.svg-container[data-loaded="true"]')

    containers.forEach((container) => {
      const svgElement = container.querySelector('svg')

      if (svgElement) {
        // 只更新尺寸，不修改其他属性
        container.style.width = iconSize.value + 'px'
        container.style.height = iconSize.value + 'px'
        container.dataset.size = iconSize.value

        svgElement.setAttribute('width', iconSize.value)
        svgElement.setAttribute('height', iconSize.value)
      } else {
        // 如果SVG不存在，尝试重新加载
        console.warn('SVG元素不存在，重新加载')
        const svgUrl = container.dataset.svgUrl
        if (svgCache.has(svgUrl)) {
          loadAndProcessSVG(container).then(() => {
            // 重新加载后应用尺寸
            const newSvgElement = container.querySelector('svg')
            if (newSvgElement) {
              container.style.width = iconSize.value + 'px'
              container.style.height = iconSize.value + 'px'
              container.dataset.size = iconSize.value
              newSvgElement.setAttribute('width', iconSize.value)
              newSvgElement.setAttribute('height', iconSize.value)
            }
          })
        }
      }
    })
  }, 10)
})

// 监听图标颜色变化
watch(iconColor, () => {
  setTimeout(() => {
    const containers = document.querySelectorAll('.svg-container[data-loaded="true"]')

    containers.forEach((container) => {
      const svgElement = container.querySelector('svg')
      if (svgElement) {
        // 获取所有图形元素，更新颜色
        const graphicElements = svgElement.querySelectorAll('path, line, circle, rect, ellipse, polygon, polyline')

        graphicElements.forEach((el) => {
          const currentStroke = el.getAttribute('stroke')
          const currentFill = el.getAttribute('fill')

          // 应用描边颜色
          if (currentStroke && currentStroke !== 'none') {
            el.setAttribute('stroke', iconColor.value)
          }

          // 应用填充颜色
          if (currentFill && currentFill !== 'none') {
            el.setAttribute('fill', iconColor.value)
          }

          // 如果既没有stroke也没有fill，默认应用颜色到fill
          if ((!currentStroke || currentStroke === 'none') && (!currentFill || currentFill === 'none')) {
            el.setAttribute('fill', iconColor.value)
          }
        })
      }
    })
  }, 10)
})
</script>
<style scoped>
@import './index.css';
</style>
